package com.looeyWei;

import javax.swing.*;
import java.awt.*;

public class SimpleDialog extends JDialog {

    JTextField input =  new JTextField(10);

    public boolean accepted = false;

    public SimpleDialog(Window owner, String title){
        super(owner, title);

        // 设置顶级面板容器
        JPanel root = new JPanel();
        this.setContentPane(root);
        root.setLayout(new BorderLayout());

        //
        JPanel panel1 = new JPanel();
        root.add(panel1, BorderLayout.CENTER);

        //
        JLabel label = new JLabel("请输入");
        panel1.add(label);

        //
        panel1.add(input);

        //
        JPanel panel2 = new JPanel();
        root.add(panel2, BorderLayout.SOUTH);
        //
        JButton okBtn = new JButton("确定");
        JButton cancelBtn = new JButton("取消");
        //
        panel2.add(okBtn);
        panel2.add(cancelBtn);

        // 点击确定按钮
        okBtn.addActionListener(e -> {
            this.accepted = true;
            this.setVisible(false); // 关闭窗口
        });

        // 店家取消按钮
        cancelBtn.addActionListener(e -> {
            this.accepted = false;
            this.setVisible(false); // 关闭窗口
        });

    }

    public String getValue(){
        return input.getText();
    }

    /**
     * execute 执行的意思
     * @return 判断用户的选择
     */
    public boolean exec(){
        //
        this.setModal(true); // 模态的(阻塞)
        this.setSize(250, 150);

        //
        centerInOwner();

        //
        this.setVisible(true);

        //
        return this.accepted;
    }

    /**
     *
     */
    private void centerInOwner(){
        // 获取原窗口的位置
        Rectangle ownerRect = this.getOwner().getBounds();

        // 显示在原窗口的中央
        int width = this.getWidth();
        int height = this.getHeight();

        int x = ownerRect.x + (ownerRect.width - width) / 2;
        int y = ownerRect.y + (ownerRect.height - height) / 2;
        this.setBounds(x, y, width, height);
    }

    private void centerInScreen(){
        // 获取屏幕的大小
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        // 显示在原窗口的中央
        int width = this.getWidth();
        int height = this.getHeight();

        int x = (screenSize.width - width) / 2;
        int y = (screenSize.height - height) / 2;
        this.setLocation(x, y);
    }
}
